package top.codedance.iotp.server.net.handle.subhandle.controller.http.sync;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.entity.UserEntity;
import top.codedance.iotp.server.ServerApplication;
import top.codedance.iotp.server.net.handle.subhandle.controller.AdapterController;
import top.codedance.iotp.server.net.handle.util.UserService;
import org.apache.log4j.Logger;

public class UserAddController extends AdapterController {

    private static Logger logger = ServerApplication.getLogger(UserAddController.class);
    public String doSubHandler(JSONObject body) {
        try {
            if (!adminVerification()) {
                return response403("No access");
            }
            JSONArray resultArr = new JSONArray();
            JSONArray objects = body.getJSONArray("users");
            JSONObject jsonObject;
            UserEntity userEntity;
            for (int i = 0; i < objects.size(); i++) {
                jsonObject = objects.getJSONObject(i);
                userEntity = new UserEntity();
                if(jsonObject.containsKey("id")){
                    userEntity.setId(jsonObject.getInteger("id"));
                }
                userEntity.setUsername(jsonObject.getString("username"));
                userEntity.setPassword(jsonObject.getString("password"));
                userEntity.setDeviceId(jsonObject.getString("deviceId"));
                userEntity.setAdmin(jsonObject.getBoolean("isAdmin"));
                UserService.add(userEntity);
                resultArr.add(userEntity);
            }
            ServerApplication.initUsersCache();
            return okResponse(resultArr.toJSONString());
        } catch (Exception e) {
            return response500("Programe exception");
        }
    }
}
